package cn.stylefeng.guns.modular.system.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.stylefeng.guns.core.common.page.LayuiPageFactory;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.util.Arith;
import cn.stylefeng.guns.modular.system.entity.*;
import cn.stylefeng.guns.modular.system.service.*;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 考试表 前端控制器
 * </p>
 *
 * @author zfy
 * @since 2020-08-10
 */
@Controller
@RequestMapping("/exam")
public class ExamController extends BaseController {

    private String PREFIX = "/modular/system/exam/";

    @Autowired
    private ExamService examService;
    @Autowired
    private ExamUserService examUserService;
    @Autowired
    private ExamPlaceService examPlaceService;
    @Autowired
    private ExamPlaceClassService examPlaceClassService;
    @Autowired
    private ExamMonthService examMonthService;
    @Autowired
    private ExamPayLogService examPayLogService;
    @Autowired
    private SysSchoolService schoolService;
    @Autowired
    private UserService userService;
    @Autowired
    private SysUserProfitService profitService;
    @Autowired
    private SysUserProfitExtractLogService extractLogService;
    @Autowired
    private SysUserProfitLogService profitLogService;
    @Autowired
    private ExamResultUserService examResultUserService;

    @RequestMapping("")
    public String exam() {
        return PREFIX + "exam.html";
    }

    @RequestMapping("exam_add")
    public String examAdd(Model model) {
        model.addAttribute("createUser",ShiroKit.getUserNotNull().getId());
        return PREFIX + "exam_add.html";
    }

    @RequestMapping("exam_edit")
    public String examEdit() {
        return PREFIX + "exam_edit.html";
    }

    @RequestMapping(value = "/examList")
    @ResponseBody
    public Object examList(@RequestParam(value = "examTitle", required = false) String examTitle,
                           @RequestParam(value = "examId", required = false) Long examId) {
        return LayuiPageFactory.createPageInfo(examService.examList(examTitle,examId));
    }

    @RequestMapping(value = "/examSave")
    @ResponseBody
    public ResponseData examSave (Exam exam){
        examService.examSave(exam);
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/examDelete")
    @ResponseBody
    public ResponseData examDelete (@RequestParam(value = "examId") Long examId){
        examService.update(new Exam(),new UpdateWrapper<Exam>().set("effective",0).eq("exam_id",examId));
        return SUCCESS_TIP;
    }

    @RequestMapping("examMonth")
    public String examMonth (){return PREFIX + "examMonth.html";};

    @RequestMapping("examMonth_add")
    public String examMonthAdd() {
        return PREFIX + "examMonth_add.html";
    }

    @RequestMapping("examMonth_edit")
    public String examMonthEdit() { return PREFIX + "examMonth_edit.html"; }

    @RequestMapping(value = "/examMonthList")
    @ResponseBody
    public Object examMonthList() {
        return LayuiPageFactory.createPageInfo(examMonthService.page(LayuiPageFactory.defaultPage(),
                new QueryWrapper<ExamMonth>()
                        .eq("effective",1)
                        .nested(qw ->
                             ShiroKit.isAdmin()?
                                    qw.isNotNull("create_user"):
                                    qw.eq("create_user",ShiroKit.getUserNotNull().getId())
                        ).orderByDesc("create_time")));
    }

    @RequestMapping(value = "/examMonthSave")
    @ResponseBody
    public ResponseData examMonthSave (ExamMonth examMonth){
        if(ToolUtil.isEmpty(examMonth.getExamMonthId())){
            examMonth.setCreateUser(ShiroKit.getUserNotNull().getId());
        }
        examMonth.setCreateTime(LocalDateTime.now());
        examMonth.setEffective(1);
        examMonthService.saveOrUpdate(examMonth);
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/examMonthDelete")
    @ResponseBody
    public ResponseData examMonthDelete (@RequestParam(value = "examMonthId") Long examMonthId ){
        examMonthService.update(new ExamMonth(),
                new UpdateWrapper<ExamMonth>().set("effective",0).eq("exam_month_id",examMonthId));
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/examMonthInfo")
    @ResponseBody
    public ResponseData examMonthInfo (@RequestParam(value = "examMonthId") Long examMonthId ){
        return ResponseData.success(examMonthService.getById(examMonthId));
    }

    @RequestMapping("examPlace")
    public String examPlace (){return PREFIX + "examPlace.html";};

    @RequestMapping("examPlace_add")
    public String examPlaceAdd() {
        return PREFIX + "examPlace_add.html";
    }

    @RequestMapping("examPlace_edit")
    public String examPlaceEdit() {
        return PREFIX + "examPlace_edit.html";
    }

    @RequestMapping(value = "/examPlaceList")
    @ResponseBody
    public Object examPlaceList() {
        IPage<Map<String,Object>> pageMaps = examPlaceClassService.pageMaps(LayuiPageFactory.defaultPage(),
                new QueryWrapper<ExamPlaceClass>().eq("effective", "1"));
        pageMaps.getRecords().forEach(map -> {
            ExamPlace examPlace = examPlaceService.getById(Long.parseLong(map.get("exam_place_id").toString()));
            map.put("place",examPlace.getPlace());
            map.put("sold_out",examPlace.getSoldOut());
        });
        return LayuiPageFactory.createPageInfo(pageMaps);
    }

    @RequestMapping(value = "/examPlaceSave")
    @ResponseBody
    public ResponseData examPlaceSave (ExamPlace examPlace,
                                       @RequestParam(value = "placeClass") String placeClass){
        List<ExamPlaceClass> examPlaceClassList = JSONArray.parseArray(placeClass, ExamPlaceClass.class);
        if(ToolUtil.isEmpty(examPlace.getExamPlaceId())){
            examPlace.setCreateUser(ShiroKit.getUserNotNull().getId());
        }
        examPlace.setCreateTime(LocalDateTime.now());
        examPlace.setEffective(1);
        examPlaceService.saveOrUpdate(examPlace);
        ExamPlace finalExamPlace = examPlaceService.getById(examPlace.getExamPlaceId());
        examPlaceClassList.forEach(examPlaceClass -> {
            BeanUtil.copyProperties(finalExamPlace,examPlaceClass);
            examPlaceClass.setPlaceClassResidueNum(examPlaceClass.getPlaceClassNum());
            examPlaceClassService.saveOrUpdate(examPlaceClass);
        });
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/examPlaceInfo")
    @ResponseBody
    public ResponseData examPlaceInfo (@RequestParam(value = "examPlaceId") Long examPlaceId ){
        return ResponseData.success(examPlaceService.getById(examPlaceId));
    }

    @RequestMapping(value = "/examPlaceClassList")
    @ResponseBody
    public ResponseData examPlaceClassList (@RequestParam(value = "examPlaceId") Long examPlaceId ){
        return ResponseData.success(examPlaceClassService.list(new QueryWrapper<ExamPlaceClass>()
                .eq("exam_place_id",examPlaceId).eq("effective",1)));
    }

    @RequestMapping(value = "/examPlaceDelete")
    @ResponseBody
    public ResponseData examPlaceDelete (@RequestParam(value = "examPlaceId") Long examPlaceId){
        examPlaceService.update(new ExamPlace(),
                new UpdateWrapper<ExamPlace>().set("effective",0).eq("exam_place_id",examPlaceId));
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/examPlaceClassDelete")
    @ResponseBody
    public ResponseData examPlaceClassDelete (@RequestParam(value = "examPlaceClassId") Long examPlaceClassId){
        examPlaceClassService.update(new ExamPlaceClass(),
                new UpdateWrapper<ExamPlaceClass>()
                        .set("effective",0).eq("exam_place_class_id",examPlaceClassId));
        return SUCCESS_TIP;
    }

    @RequestMapping("examPayLog")
    public String examPayLog (){return PREFIX + "examPayLog.html";}

    @RequestMapping("examPayLogView")
    public String examPayLogView (){return PREFIX + "examPayLogView.html";}

    @RequestMapping(value = "/examPayLogList")
    @ResponseBody
    public Object examPayLogList(Long examPayLogId ) {
        QueryWrapper<ExamPayLog> wrapper = new QueryWrapper<ExamPayLog>().eq("effective", "1");
        if(ToolUtil.isNotEmpty(examPayLogId)){
            wrapper.eq("exam_pay_log_id",examPayLogId);
        }
        IPage<Map<String,Object>> pageMaps = examPayLogService.pageMaps(LayuiPageFactory.defaultPage(),wrapper);
        pageMaps.getRecords().forEach(map -> {
            SysSchool school = schoolService.getSysSchool(Long.parseLong(map.get("create_user").toString()));
            map.put("school_name",ToolUtil.isNotEmpty(school)?school.getSchoolName():"");
            User user = userService.getOne(new QueryWrapper<User>()
                    .select(" GROUP_CONCAT(name) name")
                    .in("user_id", map.get("user_ids").toString().split(",")));
            map.put("student_name",ToolUtil.isNotEmpty(user)?user.getName():"");
            Map<String, Object> examMap = examService.getMap(new QueryWrapper<Exam>()
                    .select(" GROUP_CONCAT(exam_month_id) exam_month_ids",
                            "SUM(exam_place_cost) exam_place_cost","SUM(exam_service_cost) exam_service_cost")
                    .in("exam_id", map.get("exam_ids").toString().split(",")));
            if(!examMap.isEmpty()){
                ExamMonth examMonth = examMonthService.getOne(new QueryWrapper<ExamMonth>()
                        .select("GROUP_CONCAT(month) month ")
                        .in("exam_month_id", examMap.get("exam_month_ids").toString().split(",")));
                map.put("exam_month",ToolUtil.isNotEmpty(examMonth)?examMonth.getMonth():"");
                map.put("exam_place_cost",examMap.get("exam_place_cost").toString());
                map.put("exam_service_cost",examMap.get("exam_service_cost").toString());
            }
        });
        return LayuiPageFactory.createPageInfo(pageMaps);
    }

    @RequestMapping("paymentRecord")
    public String paymentRecord (){return PREFIX + "paymentRecord.html";}

    @RequestMapping("paymentRecord_view")
    public String paymentRecordView (){return PREFIX + "paymentRecordView.html";}

    @RequestMapping(value = "/paymentRecordList")
    @ResponseBody
    public Object paymentRecordList(String name) {
        return LayuiPageFactory.createPageInfo(examService.paymentRecord(name));
    }

    @RequestMapping("userProfit")
    public String userProfit (){return PREFIX + "userProfit.html";}

    @RequestMapping(value = "/userProfitList")
    @ResponseBody
    public Object userProfitList(String schoolName,Integer state) {
        return LayuiPageFactory.createPageInfo(profitService.userProfitList(schoolName,state));
    }

    @RequestMapping("userProfit_extract")
    public String userProfitExtract(){return PREFIX + "userProfit_extract.html";}

    @Transactional
    @RequestMapping(value = "/extractProfit")
    @ResponseBody
    public ResponseData extractProfit (Long userProfitId,Integer state,String remarks){
        profitService.update(new SysUserProfit(),
                new UpdateWrapper<SysUserProfit>().set("state",state).set("remarks",remarks)
                        .eq("user_profit_id",userProfitId));
        if(state == 3){
            SysUserProfit profit = profitService.getById(userProfitId);
            Double profitRest = profit.getUserProfitRest();
            profit.setUserProfitExtract(Arith.add(profit.getUserProfitExtract(),profitRest));
            profit.setUserProfitRest(0D);
            profitService.updateById(profit);
            extractLogService.profitExtractLogAdd(profit.getUserId(),profitRest);
        }
        return SUCCESS_TIP;
    }

    @RequestMapping("userProfit_log")
    public String userProfitLog (){return PREFIX + "userProfit_log.html";}

    @RequestMapping(value = "profitLogList")
    @ResponseBody
    public Object profitLogList (@RequestParam(value = "userId") Long userId){
        return LayuiPageFactory.createPageInfo(
                profitLogService.page(LayuiPageFactory.defaultPage(),
                        new QueryWrapper<SysUserProfitLog>().eq("user_id",userId)));
    }

    @RequestMapping("userProfit_extract_log")
    public String userProfitExtractLog(){return PREFIX + "userProfit_extract_log.html";}

    @RequestMapping(value = "profitExtractLogList")
    @ResponseBody
    public Object profitExtractLogList (@RequestParam(value = "userId") Long userId){
        return LayuiPageFactory.createPageInfo(
                extractLogService.page(LayuiPageFactory.defaultPage(),
                        new QueryWrapper<SysUserProfitExtractLog>().eq("user_id",userId)));
    }

    @RequestMapping("examResult")
    public String examResult (){return PREFIX + "examResult.html";}

    @RequestMapping("examResult_add")
    public String examResultAdd (){return PREFIX + "examResult_add.html";}

    @RequestMapping("examResult_edit")
    public String examResultEdit (){return PREFIX + "examResult_edit.html";}

    @RequestMapping(value = "examResultList")
    @ResponseBody
    public Object examResultList (@RequestParam(value = "name",required = false) String name){
        return LayuiPageFactory.createPageInfo(examResultUserService.examResultList(name));
    }

    @RequestMapping(value = "examResulSave")
    @ResponseBody
    public ResponseData examResulSave (ExamResultUser resultUser){
        examResultUserService.resultSave(resultUser);
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "examResulInfo")
    @ResponseBody
    public ResponseData examResulInfo (Long examResultUserId){
        return ResponseData.success(examResultUserService.examResulInfo(examResultUserId));
    }

    @RequestMapping(value = "examResulDel")
    @ResponseBody
    public ResponseData examResulDel (Long examResultUserId){
        examResultUserService.removeById(examResultUserId);
        return SUCCESS_TIP;
    }

    @RequestMapping("examSignUp")
    public String examSignUp (){ return PREFIX + "exam_signUp.html"; }

    @RequestMapping(value = "examSignUpList")
    @ResponseBody
    public Object examSignUpList (){
        return LayuiPageFactory.createPageInfo(examUserService.examSignUpList());
    }

}

